package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.annotations.AutoFill;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishMapper dishMapper;

    /**
     * 增加套餐
     *
     * @param setmealDTO
     */
    @Override
    @Transactional // 开启事务
    public void addSetmeal(SetmealDTO setmealDTO) {
        // dto 转化 entity
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        //存储套餐信息 并获取生成的ID
        setmealMapper.insert(setmeal);

        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        if (setmealDishes != null && setmealDishes.size() > 0) {
            for (SetmealDish setmealDish : setmealDishes) {
                // 添加套餐ID
                setmealDish.setSetmealId(setmeal.getId());

            }
            // 套餐数据添加
            setmealDishMapper.insertBatch(setmealDishes);
        }
    }

    /**
     * 分页查询
     *
     * @param setmealPageQueryDTO
     * @return
     */
    @Override
    public PageResult queryPage(SetmealPageQueryDTO setmealPageQueryDTO) {
        PageHelper.startPage(setmealPageQueryDTO.getPage(), setmealPageQueryDTO.getPageSize());
        // 查询
        Page<SetmealVO> page = setmealMapper.selectPage(setmealPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 删除套餐
     *
     * @param ids
     */
    @Override
    @Transactional // 事务
    public void delSetmeal(List<Long> ids) {
        // 验证套餐的状态
        for (Long id : ids) {
            Setmeal setmeal = setmealMapper.selectById(id);
            if (setmeal.getStatus().equals(StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        }
        for (Long id : ids) {
            // 删除套餐表数据（id）
            setmealMapper.deleteById(id);
            // 删除套餐菜品的数据（套餐id）
            setmealDishMapper.deleteByDishId(id);
        }
    }

    /**
     * 修改套餐状态
     *
     * @param status
     * @param id
     */
    @Override
    public void editStatus(Integer status, Long id) {
        //起售套餐时，判断套餐内是否有停售菜品，有停售菜品提示"套餐内包含未启售菜品，无法启售"
        if (status == StatusConstant.ENABLE) {
            //select a.* from dish a left join setmeal_dish b on a.id = b.dish_id where b.setmeal_id = ?
            List<Dish> dishList = dishMapper.getBySetmealId(id);
            if (dishList != null && dishList.size() > 0) {
                dishList.forEach(dish -> {
                    if (StatusConstant.DISABLE == dish.getStatus()) {
                        throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                    }
                });
            }
        }
        // 构造entity对象
        Setmeal setmeal = Setmeal.builder()
                .status(status)
                .id(id)
                .build();
        setmealMapper.update(setmeal);
    }

    /**
     * 获取套餐数据和关联套餐的菜品数据
     *
     * @param id
     * @return
     */
    @Override
    public SetmealVO getSetmealWithDish(Long id) {
        // 查询套餐数据 封装成entity
        Setmeal setmeal = setmealMapper.selectById(id);
        // 查询关联套餐的菜品数据  封装成List<entity>
        List<SetmealDish> setmealDishList = setmealDishMapper.selectBySetmealId(id);
        // 转换成VO并返回
        SetmealVO setmealVO = new SetmealVO();
        BeanUtils.copyProperties(setmeal, setmealVO);
        setmealVO.setSetmealDishes(setmealDishList);
        return setmealVO;
    }

    /**
     * 修改套餐数据
     *
     * @param setmealDTO
     */
    @Override
    @Transactional
    public void editSetmeal(SetmealDTO setmealDTO) {
        // dto 转化 entity
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        // 修改套餐数据
        setmealMapper.update(setmeal);
        // 获取关系菜品列表
        List<SetmealDish> setmealDishList = setmealDTO.getSetmealDishes();
        // 删除套餐关联的菜品数据
        setmealDishMapper.deleteByDishId(setmealDTO.getId());
        // 重新添加
        if (setmealDishList != null && setmealDishList.size() > 0) {
            for (SetmealDish setmealDish : setmealDishList) {
                setmealDish.setSetmealId(setmealDTO.getId());
            }
        }
        setmealDishMapper.insertBatch(setmealDishList);
    }

    /**
     * 根据分类ID查询商品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Setmeal> queryByCategory(Long categoryId) {
        return setmealMapper.selectByCategoryId(categoryId);
    }

    /**
     * 根据套餐ID查询菜品
     *
     * @param setmealId
     * @return
     */
    @Override
    public List<DishItemVO> queryDishBySetmealId(Long setmealId) {
        // 根据套餐id查询setmeal 获取份数copies 菜品描述  菜品id 菜品名称
        return setmealDishMapper.getDishItemBySetmealId(setmealId);
    }
}
